import React, { useEffect, useState } from 'react';
import { Form, Input, Select, Textarea, Dialog, TreeSelect, Checkbox } from 'tdesign-react';
import { FormProps } from 'tdesign-react';
import { JupiterPermission } from '../../../types/permissionTypes';
import { JupiterUrlResource } from '../../../types/urlResourceTypes';
import { fetchPermissionTree } from '../../../services/permissionService';
import { fetchAllUrlResources } from '../../../services/urlResourceService';
import DictionarySelect from '../../../components/Dictionary/DictionarySelect';
const { FormItem } = Form;
const { Option } = Select;

interface Props {
  visible: boolean;
  onClose: () => void;
  onSubmit: (data: Partial<JupiterPermission>) => void;
  initialData?: Partial<JupiterPermission>;
  title: string;
}

export default function PermissionForm({
  visible,
  onClose,
  onSubmit,
  initialData = {},
  title,
}: Props) {
  const [form] = Form.useForm();
  const [permissions, setPermissions] = useState<any[]>([]);
  const [permissionTree, setTermissionTree] = useState<any[]>([]);
  const [urlResources, setUrlResources] = useState<JupiterUrlResource[]>([]);
  // 获取权限列表作为父级选项
  useEffect(() => {
    if (visible) {
      fetchPermissions();
      fetchUrlResources();
    }
  }, [visible]);


  const handleSubmit: FormProps['onSubmit'] = ({ validateResult, fields }) => {
    if (validateResult === true) {
      onSubmit(fields as Partial<JupiterPermission>);
    }
  };
  const fetchPermissions = async () => {
    try {
      const response = await fetchPermissionTree();
      if (response.data) {
        setTermissionTree(response.data);
      }
    } catch (error) {
      console.error('获取权限列表失败:', error);
    }
  };

  const fetchUrlResources = async () => {
    try {
      const response = await fetchAllUrlResources();
      if (response.data) {
        setUrlResources(response.data);
      }
    } catch (error) {
      console.error('获取URL资源列表失败:', error);
    }
  };

  return (
    <Dialog
      closeOnOverlayClick={false}
      header={title}
      visible={visible}
      onClose={onClose}
      onConfirm={() => form.submit()}
      destroyOnClose
      width={600}
    >
      <Form
        form={form}
        initialData={initialData}
        layout="vertical"
        onSubmit={handleSubmit}
      >
        <FormItem
          label="权限名称"
          name="name"
          rules={[{ required: true, message: '请输入权限名称' }]}
        >
          <Input placeholder="请输入权限名称" />
        </FormItem>

        <FormItem
          label="权限编码"
          name="code"
          rules={[{ required: true, message: '请输入权限编码' }]}
        >
          <Input placeholder="请输入权限编码，如：user:create" />
        </FormItem>

        <FormItem
          label="权限类型"
          name="type"
          rules={[{ required: true, message: '请选择权限类型' }]}
          initialData={initialData?.type || "menu"}
        >
          <DictionarySelect
            dictType="permission_type"
            placeholder="请选择权限类型"
          />
        </FormItem>

        <FormItem
          label="父级权限"
          name="parentUuid"
          initialData={initialData?.parentUuid === null ? "" : initialData?.parentUuid}
        >
          <TreeSelect
            data={permissionTree}   // 这里需要树形结构数据
            clearable
            placeholder="请选择父级权限"
            keys={{
              label: 'label',
              value: 'value',
              children: 'children',
            }}
          />
        </FormItem>
        <FormItem
          label="关联URL资源"
          name="urlResourceUuids"
          initialData={initialData?.urlResourceUuids || []}
        >
          <Select
            multiple
            placeholder="请选择关联URL资源"
            style={{ width: '100%' }}
            options={urlResources}
            minCollapsedNum={3}
            keys={{ value: 'uuid', label: 'description' }}
          // collapsedItems={renderCollapsedItems}
          // size={size}
          // disabled={disabled}
          // readonly={readonly}
          />
        </FormItem>

        <FormItem
          label="图标"
          name="icon"
        >
          <Input placeholder="请输入图标名称" />
        </FormItem>

        <FormItem label="排序" name="sortIndex" initialData={0}>
          <Input placeholder="请输入排序值" type="number" />
        </FormItem>

        <FormItem label="状态" name="status" initialData={1}>
          <Select>
            <Option value={1} label="启用">
              启用
            </Option>
            <Option value={0} label="禁用">
              禁用
            </Option>
          </Select>
        </FormItem>

        <FormItem label="描述" name="description">
          <Textarea placeholder="请输入权限描述" rows={3} />
        </FormItem>
      </Form>
    </Dialog>
  );
}
